<template>
	<view>
		<u-form :model="userRegister" :rules="rules" ref="uForm" :errorType="errorType">
			<view class="bookinfo">账号信息</view>
			<view style="padding: 20rpx;">
				<u-form-item :label-position="labelPosition" label="手机号" prop="phone">
					<u-input :border="border" placeholder="请输入手机号" v-model="userRegister.phone" type="text"></u-input>
				</u-form-item>
				<u-form-item :label-position="labelPosition" label="验证码" label-width="150" prop="code">
					<u-input :border="border" placeholder="请输入验证码" v-model="userRegister.code" type="text"></u-input>
					<u-button slot="right" type="success" size="mini" @click="getCode">{{codeTips}}</u-button>
				</u-form-item>
				<u-form-item :label-position="labelPosition" label="密码" prop="password">
					<u-input :border="border" placeholder="请设置密码" v-model="userRegister.password" type="password">
					</u-input>
				</u-form-item>
				<u-form-item :label-position="labelPosition" label="确认密码" label-width="150" prop="password">
					<u-input :border="border" type="password" v-model="userRegister.rePassword" placeholder="请确认密码">
					</u-input>
				</u-form-item>
			</view>
			<view class="bookinfo">个人信息</view>
			<view style="padding: 20rpx;">
				<u-form-item :label-position="labelPosition" label="昵称" prop="name">
					<u-input :border="border" placeholder="请输入昵称" v-model="userRegister.name" type="text"></u-input>
				</u-form-item>
				<u-form-item :label-position="labelPosition" label="性别" prop="sex">
					<u-input :border="border" type="select" :select-open="actionSheetShow" v-model="userRegister.sex"
						placeholder="请选择性别" @click="actionSheetShow = true"></u-input>
				</u-form-item>
			</view>
		</u-form>
		<view style="padding: 20rpx;">
			<view class="agreement" style="padding: 20rpx;">
				<u-checkbox v-model="check" @change="checkboxChange"></u-checkbox>
				<text class="agreement-text">
					勾选代表同意时光图书馆的用户协议
				</text>
			</view>
			<!--<view class="l-body-fixed">-->
			<view style=" width: 100%; display: flex; align-items: center; justify-content: center;">
				<u-button type="primary" size="medium" @click="register()">注册</u-button>
			</view>
			<u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>
			<u-action-sheet :list="actionSheetList" v-model="actionSheetShow" @click="actionSheetCallback">
			</u-action-sheet>
		</view>
	</view>
</template>

<script>
	export default {
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		data() {
			return {
				code_md5: '',
				actionSheetList: [{
						text: '男'
					},
					{
						text: '女'
					}
				],
				actionSheetShow: false,
				check: false,
				errorType: ['message'],
				border: false,
				labelPosition: 'top',
				userRegister: { // 用户注册信息
					phone: "",
					code: "",
					password: "",
					rePassword: "",
					name: "",
					sex: "",
					agreement: false
				},
				codeTips: '',
				rules: {
					sex: [{
						required: true,
						message: '请选择性别',
						trigger: 'blur',
					}],
					name: [{
							required: true,
							message: '请输入昵称',
							trigger: 'blur',
						},
						{
							min: 1,
							max: 8,
							message: '昵称长度在1到8个字符',
							trigger: ['change', 'blur'],
						}
						// 异步验证，用途：比如用户注册时输入完账号，后端检查账号是否已存在
						// {
						// 	trigger: ['blur'],
						// 	// 异步验证需要通过调用callback()，并且在里面抛出new Error()
						// 	// 抛出的内容为需要提示的信息，和其他方式的message属性的提示一样
						// 	asyncValidator: (rule, value, callback) => {
						// 		this.$u.post('/ebapi/public_api/index').then(res => {
						// 			// 如果验证出错，需要在callback()抛出new Error('错误提示信息')
						// 			if(res.error) {
						// 				callback(new Error('姓名重复'));
						// 			} else {
						// 				// 如果没有错误，也要执行callback()回调
						// 				callback();
						// 			}
						// 		})
						// 	},
						// }
					],
					phone: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change', 'blur'],
						}
					],
					code: [{
							required: true,
							message: '请输入验证码',
							trigger: ['change', 'blur'],
						},
						{
							type: 'number',
							message: '验证码只能为数字',
							trigger: ['change', 'blur'],
						}
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: ['change', 'blur'],
						},
						{
							// 正则不能含有两边的引号
							pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]+\S{5,12}$/,
							message: '需同时含有字母和数字，长度在6-12之间',
							trigger: ['change', 'blur'],
						}
					],
					rePassword: [{
							required: true,
							message: '请重新输入密码',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								return value === this.userRegister.password;
							},
							message: '两次输入的密码不相等',
							trigger: ['change', 'blur'],
						}
					],
				},
			}
		},
		methods: {
			// 点击actionSheet回调
			actionSheetCallback(index) {
				uni.hideKeyboard();
				this.userRegister.sex = this.actionSheetList[index].text;
			},
			// 勾选版权协议
			checkboxChange(e) {
				this.userRegister.agreement = e.value;
			},
			phoneFun: function(phones) {
				//判断是否为手机号的正则表达式
				var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
				if (!myreg.test(phones)) {
					console.log('手机号格式不正确')
					return false;
				} else {
					console.log('手机号格式正确')
					return true;
				}
			},
			getCode() { // 获取验证码
				if (!this.phoneFun(this.userRegister.phone)) {
					uni.showToast({
						title: '手机号不正确',
						icon: 'none'
					});
					return;
				}

				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码',
						mask: true
					})
					setTimeout(() => {
						uni.request({
							url: this.httpRoot + 'phoneVerificationCode',
							method: 'GET',
							data: {
								phone: this.userRegister.phone
							},
							success: res => {
								console.debug(res);
								console.debug(res.data);
								var code = 0;
								var data = {};
								var message = '';
								if ('code' in res.data) {
									code = res.data.code;
								}
								if ('message' in res.data) {
									message = res.data.message;
								}
								if ('data' in res.data) {
									data = res.data.data;
									// data = res.data.data.parseJSON(); //由JSON字符串转换为JSON对象
									// data = JSON.parse(res.data.data);
									console.debug('数据：');
									console.debug(data);
									if ('code' in data) {
										this.code_md5 = data.code;
										console.debug(this.code_md5)
									}
								} else {
									uni.showToast({
										title: '服务器错误',
										icon: 'none'
									});
								}
								if (message != '') {
									uni.showToast({
										title: message,
										icon: 'none'
									});
								}

								uni.hideLoading();
								// 这里此提示会被this.start()方法中的提示覆盖
								this.$u.toast('验证码已发送');
							},
							fail: () => {
								uni.hideLoading();
								uni.showModal({
									title: '请求数据失败'
								});
							},
							complete: () => {
								// 通知验证码组件内部开始倒计时
								this.$refs.uCode.start();}
						});

					}, 2000);
				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			codeChange(text) {
				this.codeTips = text;
			},
			register() {
				console.debug('点击了注册');
				this.$refs.uForm.validate(valid => {
					if (valid) {
						console.debug('手机号' + this.userRegister.phone);
						console.debug('验证码' + this.userRegister.code);
						console.debug('密码' + this.userRegister.password);
						console.debug('密码确认' + this.userRegister.rePassword);
						console.debug('昵称' + this.userRegister.name);
						console.debug('性别' + this.userRegister.sex);
						console.debug('协议' + this.userRegister.agreement);
						console.debug('验证通过');
						if (!this.userRegister.agreement) return this.$u.toast('请勾选协议');
						if (this.userRegister.password != this.userRegister.rePassword) return this.$u.toast(
							'两次密码不一致');

						uni.request({
							url: this.httpRoot + 'register',
							method: 'POST',
							data: {
								phone: this.userRegister.phone, // 手机号
								code: this.userRegister.code, // 输入验证码
								s_code: this.code_md5, // 获取的验证码
								password: this.userRegister.password, // 密码
								nick: this.userRegister.name, // 昵称
								sex: this.userRegister.sex // 性别
							},
							success: res => {
								setTimeout(() => {
									console.debug(res);
									console.debug(res.data);
									var code = 0;
									var data = {};
									var message = '';
									if ('code' in res.data) {
										code = res.data.code;
									}
									if ('message' in res.data) {
										message = res.data.message;
									}
									if (message != '') {
										uni.showToast({
											title: message,
											icon: 'none'
										});
									}
									if (code == 200) {
										// 注册成功
										console.debug("注册：" + this.userRegister.toString());
										uni.showToast({
											title: '注册成功'
										});
										setTimeout(() => {
											uni.navigateBack({
												delta: 1
											})
										}, 2000);
									} else if (code == 500) {
										uni.showToast({
											title: '已经注册',
											icon: 'none'
										});
									} else if (code == 403) {
										uni.showToast({
											title: '注册失败',
											icon: 'none'
										});
									}
								}, 1000);
							},
							fail: () => {
								uni.showModal({
									content: '连接服务器失败'
								});
							},
							complete: () => {

							}
						});
					} else {
						console.debug('验证失败');
					}
				});
			}
		}
	}
</script>

<style>
	page {
		background-color: #FFFFFF;
	}

	.l-body-fixed {
		position: fixed;
		bottom: 0;
		left: 0;
		height: 98rpx;
		display: flex;
		width: 100%;
		padding: 0 var(--pad-lr);
		align-items: center;
		white-space: nowrap;
		background-color: #f7f7fa;
		justify-content: space-between;
	}

	.bookinfo {
		padding: 20rpx;

		display: flex;
		align-items: center;
		justify-content: space-between;

		font: bold 36rpx normal;
	}
</style>
